/**
 * @name Home
 * @author darcrand
 * @desc 首页,项目列表
 */

import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { inject, observer } from 'mobx-react'
import { Row, Col, Avatar } from 'antd'
import moment from 'moment'
import { PlusOutlined } from '@ant-design/icons'
import { bindReachBottom } from '@/utils'

import { TopBar } from '@/components'
import { apiGetProjects } from '@/apis/project'
import { CREATE_MODE_ID } from '@/pages/ProjectEdit'

import styles from './styles.module.less'

const serverUrl = process.env.REACT_APP_SERVER_URL

@inject('counter', 'user')
@observer
class Home extends Component {
  state = { list: [], total: 0, page: 1 }
  unBindBottomHandler = null

  componentDidMount() {
    this.getList()
    this.unBindBottomHandler = bindReachBottom(this.onBottom, { offset: 100 })
  }

  componentWillUnmount() {
    this.unBindBottomHandler && this.unBindBottomHandler()
  }

  getList = async () => {
    const { list, page } = this.state
    try {
      const { list: arr, total } = await apiGetProjects({ page: this.state.page })
      const transforList = arr.map(v => ({
        ...v,
        date: moment(v.updatedAt).calendar(),
        owner: { avatar: serverUrl + v.owner.avatar, nickname: v.owner.nickname },
      }))
      this.setState({ list: page === 1 ? transforList : list.concat(transforList), total })
    } catch (err) {}
  }

  onBottom = () => {
    const { list, total, page } = this.state
    if (list.length < total) {
      this.setState({ page: page + 1 }, this.getList)
    }
  }

  render() {
    const { list } = this.state
    return (
      <>
        <TopBar />

        <Row className={styles.row}>
          <Col xs={24} sm={12} md={8} lg={6} xl={6} xxl={4}>
            <Link to={`/project-edit/${CREATE_MODE_ID}`}>
              <section className={styles.item_add}>
                <PlusOutlined style={{ fontSize: 40 }} />
                <span>add your new project</span>
              </section>
            </Link>
          </Col>

          {list.map(v => (
            <Col key={v._id} xs={24} sm={12} md={8} lg={6} xl={6} xxl={4}>
              <Link to={`/project/${v._id}`}>
                <section className={styles.item}>
                  <p className={styles.title} style={{ backgroundColor: v.bgColor }}>
                    {v.title}
                  </p>
                  <p className={styles.desc}>{v.desc}</p>
                  <div className={styles.info}>
                    <Avatar src={v.owner.avatar} style={{ flexShrink: 0 }} />
                    <span className={styles.nickname}>{v.owner.nickname}</span>
                    <span className={styles.date}>{v.date}</span>
                  </div>
                </section>
              </Link>
            </Col>
          ))}
        </Row>
      </>
    )
  }
}

export default Home
